﻿using System;
using System.ServiceModel;
using ExplorerService.Managers;

namespace ExplorerService.Communication
{
    /// <summary>
    /// Template for session based client services. Makes sure the service is closed when the client session ends.
    /// </summary>
    public abstract class ClientSessionMonitoredService : IDisposable
    {
        /// <summary>
        /// Stores the session ID
        /// </summary>
        private Guid _sessionId = Guid.Empty;

        /// <summary>
        /// Stores the session ID
        /// </summary>
        protected Guid SessionId
        {
            get { return _sessionId; }
        }

        /// <summary>
        /// Verifies the session ID and adds the current operation context to the monitored session list
        /// </summary>
        /// <param name="sessionId"></param>
        protected void VerifySessionIdAndRegister(Guid sessionId)
        {
            if (!ClientSessionManager.Instance.ValidSessionId(sessionId))
            {
                throw new Exception("Invalid session ID.");
            }
            _sessionId = sessionId;
            if (OperationContext.Current == null) return;
            var currentSession = ClientSessionManager.Instance[sessionId];
            currentSession.SessionOperationContexts.Add(OperationContext.Current);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            ServiceDispose();
        }

        /// <summary>
        /// Method called to clean up service resources
        /// </summary>
        protected abstract void ServiceDispose();
    }
}